package com.pug.config.interceptor;

import com.pug.annotation.EnableNoToken;
import com.pug.constant.PugContants;
import com.pug.pojo.KssUser;
import com.pug.result.ResultEnum;
import com.pug.result.ex.KsdValidationException;
import com.pug.threadlocal.UserThreadLocal;
import com.pug.utils.fn.asserts.Vsserts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 飞哥
 * @Title: 学相伴出品
 * @Description: 飞哥B站地址：https://space.bilibili.com/490711252
 * 记得关注和三连哦！
 * @Description: 我们有一个学习网站：https://www.kuangstudy.com
 * @date 2022/3/6$ 2:51$
 */
@Component
@Slf4j
public class PassportTokenInterceptor implements HandlerInterceptor, PugContants {

    @Autowired
    private com.pug.redis.PugRedisOperator redisOperator;
    @Resource
    RedisTemplate<String,KssUser> redisTemplateUser;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //检查是否带有EnableNoToken注解
        //ResourceHttpRequestHandler
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod=(HandlerMethod) handler;
            EnableNoToken methodAnnotation = handlerMethod.getMethodAnnotation(EnableNoToken.class);
            if(methodAnnotation!=null&&methodAnnotation.value()==true)
                return true;
        }
        // 1: 获取前台接口调用请求头中的用户和token参数
        String authUserId = request.getHeader("AuthUserId");
        String authToken = request.getHeader("AuthToken");
        String a = request.getHeader("userId");
        String b = request.getHeader("token");
        // 2: 如果token和userId是空的，就直接返回
        if (Vsserts.isNotEmpty(authUserId) && Vsserts.isNotEmpty(authToken)) {
            // 根据用户id查询缓存中的token
            String redisToken = redisOperator.get(PUG_XQ_LOGIN_USER_TOKEN  + authUserId);
            // 如果是空，则去登录
            if (Vsserts.isEmpty(redisToken)) {
                //直接在前台响应地方跳转到登录去
                throw new KsdValidationException(ResultEnum.LOGIN_FAIL);
            }
            // 如果不是空，说明用户前台app或者小程序传递了token，
            // 把传递进来的token和缓存中的token进行比较看是否一致
            // google浏览器：说明它肯定退出一次然后又登录了 user:1 token 545454545
            // firefox浏览器：说明它肯定退出一次然后又登录了 user:1 token 878787878
            if (!redisToken.equalsIgnoreCase(authToken)) {
                throw new KsdValidationException(ResultEnum.SAME_LOGIN);
            }
        } else {
            throw new KsdValidationException(ResultEnum.LOGIN_FAIL);
        }
        //ThreadLocal 保存用户信息
        KssUser kssUser = redisTemplateUser.opsForValue().get(PUG_XQ_LOGIN_USER_INFO + authUserId);
        UserThreadLocal.put(kssUser);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserThreadLocal.remove();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
